/**
 * jims
 */
package com.jims.master.modules.doctor.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.*;
import com.jims.master.modules.doctor.entity.*;
import com.jims.master.modules.doctor.vo.SaveDataVo;
import com.jims.master.modules.finance.dao.InpBillDetailDao;
import com.jims.master.modules.finance.entity.InpBillDetail;
import com.jims.master.modules.oper.dao.ClinicItemDictDao;
import com.jims.master.modules.oper.dao.ClinicVsChargeDao;
import com.jims.master.modules.oper.dao.PriceListDao;
import com.jims.master.modules.oper.entity.ClinicItemDict;
import com.jims.master.modules.oper.entity.PriceList;
import com.jims.master.modules.orders.dao.OrdersDao;
import com.jims.master.modules.orders.entity.Orders;
import com.jims.master.modules.orders.service.OrdersService;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DeptUtils;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 检验申请Service
 * @author 陈晓阳
 * @version 2017-03-16
 */
@Service
@Transactional(readOnly = true)
public class LabApplyService extends CrudService<LabApplyDao, LabApply> {

    @Autowired
    private LabItemDao labItemDao;
    @Autowired
    private ExamApplyService examApplyService;
    @Autowired
    private ClinicItemDictDao clinicItemDictDao;
    @Autowired
    private LabItemService labItemService;
    @Autowired
    private LabApplyDao labApplyDao;
    @Autowired
    private PriceListDao priceListDao;
    @Autowired
    private InpBillDetailDao inpBillDetailDao;
    @Autowired
    private OutpTreatRecDao outpTreatRecDao;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private PatVisitService patVisitService;

    @Autowired
    private ClinicVsChargeDao clinicVsChargeDao;
    @Autowired
    private ClinicMasterService clinicMasterService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ClinicMasterDao clinicMasterDao;
    @Autowired
    private HisDiagnosisDao hisDiagnosisDao;
    @Autowired
    private OrgDeptDao orgDeptDao;
    @Autowired
    private PatVisitDao patVisitDao;
    @Autowired
    private OrdersDao ordersDao;


    public LabApply get(String id) {
        return super.get(id);
    }

    public List<LabApply> findList(LabApply labApply) {
        return super.findList(labApply);
    }

    public Page<LabApply> findPage(Page<LabApply> page, LabApply labApply) {
        return super.findPage(page, labApply);
    }

    @Transactional(readOnly = false)
    public int save(LabApply labApply) {
        return super.save(labApply);
    }

    @Transactional(readOnly = false)
    public int delete(LabApply labApply) {
        return super.delete(labApply);
    }

    /**
     * 查询此个病人的所有待做和未做的检验项目
     *
     * @param labItemPage
     * @param labItem
     * @return
     * @author 陈晓阳
     */
    public Page<LabItem> queryLabByPatient(Page<LabItem> labItemPage, LabItem labItem) {
        labItem.updateOrgId();
        labItem.setPage(labItemPage);
        List<LabItem> lbsItems = this.labItemDao.queryExamByPatient(labItem.getLabApply().getPatientId(), UserUtils.getOrgId(), labItem.getItemName());
        labItemPage.setList(lbsItems);
        return labItemPage;
    }

    /**
     * 检验申请保存
     *
     * @param labItem
     * @return
     * @author 陈晓阳
     */

    @Transactional(readOnly = false)
    public int saveLabApplyData(LabItem labItem) {
        User user = UserUtils.getUser();
        Integer resultVal = 0;
        //1 保存检验申请主表与检验申请明细
        LabApply labApply = saveLabApply(labItem);
        labItem.setLabApply(labApply);
        //2 保存子表
        List<SaveDataVo> saveDataVos = this.saveLabItems(labItem);//多条记录 对应诊疗项目
        //将clinicmaster里面的科室添加到saveDataVos实体

        //修改clinic_master挂号状态


        resultVal = saveDataVos.size();
        if ("0".equals(labApply.getInoroutFlag())) {
            ClinicMaster clinicMaster = clinicMasterService.get(labApply.getClinicId());
            //修改clinic_master挂号状态
            String doctorId = clinicMaster.getDoctorId();
            if (StringUtils.isBlank(doctorId)) {
                clinicMaster.setDoctorId(user.getId());
                clinicMaster.setClinicType("1");
            }
            clinicMasterService.updateClinicType(clinicMaster);
            for (SaveDataVo saveDataVo : saveDataVos) {
                saveDataVo.setApplyDept(clinicMaster.getDeptId());
            }
            // /2 保存处置治疗|| 门诊代收费表数据
            Map<String, Object> map = this.examApplyService.commonSave(saveDataVos);
            //3 更新ordersId
            labApply.setOrdersId((String) map.get("ordersId"));
            this.save(labApply);
            resultVal = (Integer) map.get("rows");
        } else {
            PatVisit patVisit = this.patVisitService.get(labItem.getLabApply().getVisitId());
            //住院
            String[] clincItemIds = labItem.getClinicItemIds().split(",");
            for (String clinicItemId : clincItemIds) {
                ClinicItemDict clinicItemDict = this.clinicItemDictDao.get(clinicItemId);
                Orders saveData = new Orders();
                saveData.setApplyId(labItem.getLabApply().getId());
                saveData.setOrderText(clinicItemDict.getItemName());
                saveData.setOrderClass(clinicItemDict.getItemClass());
                saveData.setClinicItemId(clinicItemDict.getId());
                saveData.setBillingAttr("0");
                saveData.setOrderStatus("1");//传输状态
                saveData.setWardCode(patVisit.getWardCode());
                saveData.setPatientId(labItem.getLabApply().getPatientId());
                saveData.setPerformedBy(labItem.getLabApply().getImplementDept());
                saveData.setVisitId(labItem.getLabApply().getVisitId());
                saveData.setRepeatIncaditor("0");
                saveData.setIsApply("1");
                saveData.setNewDept(labItem.getLabApply().getBillingDept());
                ordersService.save(saveData);
            }
        }

        return resultVal;
    }

    /**
     * 检验申请明细保存
     *
     * @param labItem
     * @return
     * @author 陈晓阳
     */
    private List<SaveDataVo> saveLabItems(LabItem labItem) {
        List<SaveDataVo> resultVal = new ArrayList<SaveDataVo>();
        String[] clincItemIds = labItem.getClinicItemIds().split(",");
        for (String clinicItemId : clincItemIds) {
            ClinicItemDict clinicItemDict = this.clinicItemDictDao.get(clinicItemId);
            LabItem saveData = new LabItem();
            saveData.setApplyId(labItem.getLabApply().getId());
            saveData.setItemName(clinicItemDict.getItemName());
            saveData.setItemCode(clinicItemDict.getItemCode());
            saveData.setClinicItemId(clinicItemDict.getId());
            double price = this.clinicItemDictDao.findPriceById(clinicItemDict.getId());
            saveData.setCosts(price + "");
            this.labItemService.save(saveData);
            SaveDataVo saveDataVo = new SaveDataVo();
            saveDataVo.setPatientId(labItem.getLabApply().getPatientId());
            saveDataVo.setItemName(clinicItemDict.getItemName());
            saveDataVo.setImplementDept(labItem.getLabApply().getImplementDept());
            saveDataVo.setChargeFlag(labItem.getLabApply().getChargeFlag());
            saveDataVo.setConfirmFlag(labItem.getLabApply().getConfirmFlag());
            saveDataVo.setClinicId(labItem.getLabApply().getClinicId());
            saveDataVo.setNum(1);
            saveDataVo.setClinicItemId(clinicItemDict.getId());
            saveDataVo.setApplyId(labItem.getLabApply().getId());
            saveDataVo.setSumPrice(price);
            saveDataVo.setItemClass(clinicItemDict.getItemClass());
            saveDataVo.setIsApply("1");
            saveDataVo.setApplyNo(labItem.getLabApply().getApplyOn());
            saveDataVo.setRcptNo("");//收费号
            saveDataVo.setImplementUser("");//执行人
            saveDataVo.setInoroutFlag("0");
            resultVal.add(saveDataVo);
        }
        return resultVal;
    }

    /**
     * 检验申请保存单表
     *
     * @param labItem
     * @return
     * @author 陈晓阳
     */
    @Transactional(readOnly = false)
    private LabApply saveLabApply(LabItem labItem) {
        LabApply labApply = labItem.getLabApply();
        if ("0".equals(labApply.getInoroutFlag())) {
            labApply.setApplyOn(NumberUtils.getClinicLab(labItem.getLabApply().getClinicId()));
            ;//申请序号
        } else {
            labApply.setApplyOn(NumberUtils.getClinicLabIn(labApply.getVisitId()));//申请序号
        }
        labApply.setConfirmFlag("0");
        labApply.setChargeFlag("0");
        labApply.setBillingDept(UserUtils.getUser().getOrgDept().getId());
        this.save(labApply);
        return labApply;
    }

    /**
     * 删除检验申请
     *
     * @param labApply
     * @return
     * @author 陈晓阳
     */
    @Transactional(readOnly = false)
    public int deleteAllData(LabApply labApply) {
        int resultVal = 0;
        resultVal += this.labItemService.deleteByApplyId(labApply.getId());
        this.examApplyService.commonDel(labApply.getOrdersId());
        resultVal += this.deleteLabApplyById(labApply.getId());
        return resultVal;
    }

    /**
     * 根据Id删除检验申请主表数据
     *
     * @param id
     * @return
     * @author 陈晓阳
     */
    @Transactional(readOnly = false)
    private int deleteLabApplyById(String id) {
        return this.labApplyDao.deleteLabApplyById(id);
    }

    /**
     * 执行确认操作
     *
     * @param labApply
     * @return
     */
    @Transactional(readOnly = false)
    public int labConfirmDo(LabApply labApply) {
        int sum = 0;
        if (labApply.getInoroutFlag() != null && labApply.getInoroutFlag().equals("0")) {
            OutpTreatRec outpTreatRec = new OutpTreatRec();
            outpTreatRec.setOrdersId(labApply.getOrdersId());
            outpTreatRecDao.ConfirmDo(outpTreatRec);
            sum = this.labApplyDao.labConfirmDo(labApply.getId(), UserUtils.getUser().getId());
        } else if (labApply.getInoroutFlag() != null && labApply.getInoroutFlag().equals("1")) {
            Orders orders = new Orders();
            orders.setApplyId(labApply.getId());
            List<Orders> Orderses = ordersDao.getOrders(orders);
            sum = labConfirmInHos(labApply, Orderses);
            if (sum != 0) {
                labApplyDao.labConfirmInHos(labApply.getId());
            }
        }
        return sum;
    }

    /**
     * 取消确认执行
     *
     * @param labApply
     * @return
     * @author 赵宁
     */
    @Transactional(readOnly = false)
    public int cancelLabConfirmDo(LabApply labApply) {
        int sum = 0;
        if (labApply.getInoroutFlag() != null && labApply.getInoroutFlag().equals("0")) {
            OutpTreatRec outpTreatRec = new OutpTreatRec();
            outpTreatRec.setOrdersId(labApply.getOrdersId());
            outpTreatRecDao.cancelConfirmDo(outpTreatRec);
            sum = this.labApplyDao.cancelLabConfirmDo(labApply.getId(), UserUtils.getUser().getId());
        } else if (labApply.getInoroutFlag() != null && labApply.getInoroutFlag().equals("1")) {
            Orders orders = new Orders();
            orders.setApplyId(labApply.getId());
            List<Orders> orderses = ordersDao.getOrders(orders);
            if (orderses.size() > 0) {
                for (int i = 0; i < orderses.size(); i++) {
                    InpBillDetail inpBillDetail = new InpBillDetail();
                    String ordersId = orderses.get(i).getId();
                    inpBillDetail.setOrdersId(ordersId);
                    sum += inpBillDetailDao.deleteInpDetails(inpBillDetail);//根据医嘱id删除收费明细记录
                }
            }

            if (sum != 0) {
                labApplyDao.cancelLabConfirmInHos(labApply.getId());
            }
        }
        return sum;
    }

    /**
     * 检验确认--住院
     *
     * @param labApply
     * @return
     * @author 赵宁
     */
    @Transactional(readOnly = false)
    public int labConfirmInHos(LabApply labApply, List<Orders> orderses) {
        int code = 0;
        List<LabItem> labItems = labItemDao.queryByApplyId(labApply.getId());
        if (labItems != null && labItems.size() > 0) {
            for (int i = 0; i < labItems.size(); i++) {
                String clinciId = labItems.get(i).getClinicItemId();
                String ordersId = orderses.get(i).getId();
                List<PriceList> priceLists = priceListDao.findListPrice(clinciId);
                if (priceLists != null && priceLists.size() > 0) {
                    for (int j = 0; j < priceLists.size(); j++) {
                        PriceList priceList = priceLists.get(j);
                        InpBillDetail inpBillDetail = new InpBillDetail();
                        inpBillDetail.setOrdersId(ordersId);
                        inpBillDetail.setVisitId(labApply.getVisitId());
                        inpBillDetail.setPatientId(labApply.getPatientId());
                        inpBillDetail.setPriceId(priceList.getId());
                        inpBillDetail.setItemClass(priceList.getItemClass());
                        inpBillDetail.setItemCode(priceList.getItemCode());
                        inpBillDetail.setItemName(priceList.getItemName());
                        inpBillDetail.setItemSpec(priceList.getItemSpec());
                        inpBillDetail.setAmount(priceList.getAmount() + "");
                        inpBillDetail.setUnits(priceList.getUnits());
                        inpBillDetail.setItemPrice(priceList.getPrice());
                        inpBillDetail.setCosts(priceList.getPrice() * priceList.getAmount());
                        inpBillDetail.setCharges(priceList.getPrice() * priceList.getAmount());
                        inpBillDetail.setOrderDept(labApply.getBillingDept());
                        inpBillDetail.setOrderDoctor(labApply.getCreateBy().getId());
                        inpBillDetail.setPriceQuotiety("1");
                        inpBillDetail.setPerformDept(labApply.getImplementDept());
                        inpBillDetail.setClassOnReckoning(priceList.getClassOnReckoning());
                        inpBillDetail.setSubjCode(priceList.getSubjCode());
                        inpBillDetail.setClassOnMr(priceList.getClassOnMr());
                        inpBillDetail.setOrgId(labApply.getOrgId());
                        inpBillDetail.setPriceId(priceList.getId());
                        inpBillDetail.setPerformPerson(UserUtils.getUser().getId());
                        inpBillDetail.setDeptStayed(UserUtils.getUser().getOrgDept().getId());
                        inpBillDetail.setWardCode(UserUtils.getUser().getOrgDept().getId());
                        inpBillDetail.preInsert();
                        code = inpBillDetailDao.insert(inpBillDetail);
                    }
                }
            }
        }
        return code;
    }

    /**
     * 退费
     *
     * @param labApply
     * @return
     */
    @Transactional(readOnly = false)
    public int refundIng(LabApply labApply) {
        int num = labApplyDao.refundIng(labApply);
        return num;
    }

    /**
     * 护士端--未尽检验项目
     *
     * @param visitId
     * @return
     * @author 赵宁
     */
    public List<LabApply> getUnfinishedLab(String visitId) {
        return labApplyDao.getUnfinishedLab(visitId);
    }

    /**
     * 检验单打印
     *
     * @param labApply
     * @return
     * @author CTQ
     */
    public String printLabApply(LabApply labApply, User user) {
        String printPath = "";
        Map map = new HashMap();
        if (StringUtils.isNotBlank(labApply.getId())) {
            map.put("testNo", labApply.getApplyOn());
            map.put("name", labApply.getName());
            map.put("sex", DictUtils.getDictLabel(labApply.getPatMasterIndex().getSex(), "SEX_DICT", ""));
            map.put("age", labApply.getPatMasterIndex().getAge());
            map.put("specimen", DictUtils.getDictLabel(labApply.getSpecimen(), "SPECIMAN_DICT", ""));//标本
            if (StringUtils.isNotBlank(labApply.getVisitId())) {
                PatVisit patVisit = patVisitService.get(labApply.getVisitId());
                map.put("deptName", DeptUtils.getDeptName(patVisit.getDeptAdmissionTo(), ""));
            } else {
                map.put("deptName", "");
            }
            List<BaseDto> list = labItemDao.findItemByApplyId(labApply.getId(), user.getOrgId());
            map.put("lists", list);
            printPath = PrintPdfUtils.previewPdf(user.getId(), "his/nurse/labTest/LabTestNurses.jasper", map, list, "LabTestNurses");

        }
        return printPath;
    }

    /**
     * 检验打印
     *
     * @param clinicId
     * @param visitId
     * @param patientId
     * @param labId
     * @return
     */
    public String printPresc(String clinicId, String visitId, String patientId, String labId) {
        UserUtils userUtils = new UserUtils();
        Map map = new HashMap();
        String hospital = companyDao.get(userUtils.getUser().getOrgId()).getOrgName();
        LabApply labApply = labApplyDao.getPrintInfo(labId);
        ClinicMaster clinicMaster = new ClinicMaster();
        String url = "";
        HisDiagnosis hisDiagnosis = new HisDiagnosis();
        if (!"".equals(clinicId) && clinicId != null) {
            clinicMaster = clinicMasterDao.getPrintInfo(patientId);
            String sex = clinicMaster.getSex();
            map.put("sex", sex);
            map.put("age", clinicMaster.getAge());
            map.put("clinicNo", clinicMaster.getClinicNo());
            map.put("name", clinicMaster.getName());//患者姓名
            hisDiagnosis.setClinicId(clinicId);
            url = "his/labTest/clinicLabTest/clinicLabTest.jasper";
        } else {
            PatVisit patVisit = patVisitDao.getPrintInfo(visitId);
            map.put("inpNo", patVisit.getVisitNo());
            map.put("bedNo", patVisit.getBedNo());
            map.put("name", patVisit.getPatVisitIndex().getName());//患者姓名
            map.put("sex", patVisit.getPatVisitIndex().getSex());
            map.put("age", patVisit.getPatVisitIndex().getAge());
            hisDiagnosis.setVisitId(visitId);
            url = "his/labTest/hosLabTest/HOSLabTest.jasper";
        }


        String hisDiagnosi = "";
        List<HisDiagnosis> list1 = hisDiagnosisDao.findList(hisDiagnosis);
        for (int i = 0; i < list1.size(); i++) {
            hisDiagnosi += list1.get(i).getIcdName() + ",";
        }
        map.put("chubuzhenduan", hisDiagnosi);//临床诊断
        map.put("hospital", hospital);
        map.put("deptName", orgDeptDao.get(labApply.getBillingDept()).getDeptName());//申请科室
        map.put("userName", userUtils.getUser().getName());//申请医生
        map.put("performedBy", orgDeptDao.get(labApply.getImplementDept()).getDeptName()); // 执行科室
        map.put("labNo", labApply.getApplyOn());//申请号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        map.put("date", sdf.format(labApply.getCreateDate()));
        map.put("specimen", labApply.getSpecimen());
        List<BaseDto> baseDtoList = labApplyDao.getLabItemName(labId);
        String printPath = PrintPdfUtils.previewPdf(userUtils.getUser().getId(), url, map, baseDtoList, "lab");
        return printPath;
    }


    @Transactional(readOnly = false)
    public int inpRetCharge(LabApply labApply) {
        int num = 0;
        String applyId = labApply.getId();
        if ("1".equals(labApply.getChargeFlag())) {
            num = dao.inpOutpRet("5", applyId); // 修改退费状态  3:已退；5申请
        } else {
        }
        return num;

    }


    @Transactional(readOnly = false)
    public int retChargeOk(Orders orders) {
        int num = 0;
//        examItemDao.deleteByApplyId(orders.getApplyId());
        List<Orders> ordersList = ordersDao.getOrders(orders);
        ordersDao.inpRetCharge("1", orders.getApplyId());
        for (Orders order : ordersList) {
            InpBillDetail inpBillDetail = new InpBillDetail();
            inpBillDetail.updateOrgId();
            inpBillDetail.setOrdersId(order.getId());
            List<InpBillDetail> inpBillDetailList = inpBillDetailDao.getApplyitem(inpBillDetail);
            for (InpBillDetail detail : inpBillDetailList) {
                int amonut = -1 * (Integer.valueOf(detail.getAmount()));
                detail.setAmount(amonut + "");
                detail.setCosts(-1 * (detail.getCosts()));
                detail.setCharges(-1 * (detail.getCharges()));
                detail.setPerformPerson(UserUtils.getUser().getName());
                detail.preInsert();
                inpBillDetailDao.insert(detail);
            }
        }
        num = dao.inpOutpRet("2", orders.getApplyId());
        return num;
    }

}